package com.boful.convert.core.impl.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.log4j.Logger;

import com.boful.convert.core.TranscodeEvent;
import com.boful.convert.model.DiskFile;

public class SwfTools {

	private static Logger logger = Logger.getLogger(SwfTools.class);

	public static void transcode(String pdf2swfPath, DiskFile srcFile,
			DiskFile destFile, TranscodeEvent transcodeEvent, String jobId) {
		// System.out.println("pdf2swfPath:"+pdf2swfPath+"------------exsit:"+srcFile.exists());
		// System.out.println("pdf path:"+srcFile.getAbsolutePath()+"-------exsit:"+srcFile.exists());
		// System.out.println("swftools:-------" + destFile.getAbsolutePath());
		if (!srcFile.exists()) {
			if (transcodeEvent != null) {
				transcodeEvent.onTranscodeFail(srcFile, "文件不存在!", jobId);
				return;
			}
		}
		if (destFile.exists()) {
			destFile.delete();
		}
		try {
			destFile.createNewFile();
		} catch (IOException e1) {
			transcodeEvent.onTranscodeFail(srcFile, e1.getMessage(), jobId);
			return;
		}
		Runtime runtime = Runtime.getRuntime();
		StringBuffer cmd = new StringBuffer(pdf2swfPath + " ");
		cmd.append(srcFile.getAbsolutePath() + " ");
		cmd.append("-o " + destFile.getAbsolutePath() + " ");
		cmd.append("-T 9 -f  ");
		cmd.append(" -G -s poly2bitmap");
		// cmd.append(" -G ");
		if (transcodeEvent != null) {
			transcodeEvent.onStartTranscode(srcFile, jobId);
		}
		try {
			System.out.println("命令行:" + cmd);
			logger.debug("命令行:" + cmd);
			Process process = runtime.exec(cmd.toString());
			Thread thread = new Thread(new ReadProcessThread(process));
			thread.start();
			process.waitFor();
			if (destFile.exists() && destFile.length() > 0) {
				if (transcodeEvent != null) {
					transcodeEvent.onTranscodeSuccess(srcFile, destFile, jobId);
				}

				return;
			} else {
				if (transcodeEvent != null) {
					transcodeEvent.onTranscodeFail(srcFile, "失败", jobId);
				}
			}

			if (destFile.length() == 0) {
				destFile.delete();
			}
		} catch (IOException | InterruptedException e) {
			logger.debug(e.getMessage());
			if (transcodeEvent != null) {
				transcodeEvent.onTranscodeFail(srcFile, e.getMessage(), jobId);
			}
		}
	}
}
